const ElementUI = require('element-ui')
let loading = null

const fn = {
  DATE_MILLISECOND_YEAR: 31557600000,
  DATE_MILLISECOND_MONTH: 2629800000,
  DATE_MILLISECOND_DAY: 86400000,
  DATE_MILLISECOND_HOUR: 3600000,
  DATE_MILLISECOND_MINUTE: 60000,
  DATE_MILLISECOND_SECOND: 1000,
  showLoading() {
    loading = ElementUI.Loading.service({
      lock: true,
      spinner: 'el-icon-loading',
      background: 'rgba(255, 255, 255, 0.7)'
    })
  },
  hideLoading() {
    loading && loading.close()
  },
  showWarningToast(msg) {
    ElementUI.Message({type: 'warning', message: msg, showClose: true})
  },
  showSuccessToast(msg) {
    ElementUI.Message({type: 'success', message: msg})
  },
  showErrorToast(msg) {
    ElementUI.Message({type: 'error', message: msg, showClose: true})
  },
  showInfoToast(msg) {
    ElementUI.Message({type: 'info', message: msg, showClose: true})
  },
  /**
   * 确认框
   * @param {*} message
   * @param {*} confirmText
   * @param {*} cancelText
   * @param {*} distinguishCancelAndClose
   */
  confirm(message, confirmText = '确认？', cancelText = '取消', distinguishCancelAndClose = false, showCancelButton = true) {
    return new Promise((resolve) => {
      ElementUI.MessageBox.confirm(message, '提示', {
        confirmButtonText: confirmText,
        cancelButtonText: cancelText,
        distinguishCancelAndClose: distinguishCancelAndClose,
        type: 'warning',
        showCancelButton: showCancelButton
      }).then(() => {
        return resolve(1)
      }).catch(action => {
        return resolve(action === 'cancel' ? 0 : -1)
      })
    })
  },
  /**
   * 成功提示框
   * @param {*} message
   * @param {*} confirmButtonText
   * @param {*} distinguishCancelAndClose
   * @param {*} dangerouslyUseHTMLString
   */
  showSuccessAlert(message, confirmButtonText, distinguishCancelAndClose = false, dangerouslyUseHTMLString = false) {
    return new Promise((resolve) => {
      ElementUI.MessageBox.confirm(message, '提示', {
        confirmButtonText: confirmButtonText,
        cancelButtonText: '',
        distinguishCancelAndClose: distinguishCancelAndClose,
        dangerouslyUseHTMLString: dangerouslyUseHTMLString,
        type: 'success',
        showCancelButton: false
      }).then(() => {
        return resolve(1)
      }).catch(action => {
        return resolve(action === 'cancel' ? 0 : -1)
      })
    })
  },
  /**
   * 信息提示框
   * @param {*} message
   * @param {*} confirmButtonText
   * @param {*} distinguishCancelAndClose
   * @param dangerouslyUseHTMLString
   */
  showInfoAlert(message, confirmButtonText, distinguishCancelAndClose = false, dangerouslyUseHTMLString = false) {
    return new Promise((resolve) => {
      ElementUI.MessageBox.confirm(message, '提示', {
        confirmButtonText: confirmButtonText,
        cancelButtonText: '',
        distinguishCancelAndClose: distinguishCancelAndClose,
        dangerouslyUseHTMLString: dangerouslyUseHTMLString,
        type: 'info',
        showCancelButton: false
      }).then(() => {
        return resolve(1)
      }).catch(action => {
        return resolve(action === 'cancel' ? 0 : -1)
      })
    })
  },
  formatDate(tempDate, fmt) {
    const o = {
      'M+': tempDate.getMonth() + 1, // 月份
      'd+': tempDate.getDate(), // 日
      'h+': tempDate.getHours(), // 小时
      'm+': tempDate.getMinutes(), // 分
      's+': tempDate.getSeconds(), // 秒
      'q+': Math.floor((tempDate.getMonth() + 3) / 3), // 季度
      'S': tempDate.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (tempDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[
          k]).length)))
      }
    }
    return fmt
  },
  getDateByString(dateString) {
    if (dateString.indexOf('-')) {
      return new Date(dateString.replace(/-/g, '/'))
    }
  },
  getShowAllTime(dateLongValue) {
    return this.formatDate(new Date(parseInt(dateLongValue)), 'yyyy-MM-dd hh:mm:ss')
  },
  getShowTime(dateLongValue) {
    return this.formatDate(new Date(parseInt(dateLongValue)), 'yyyy-MM-dd hh:mm')
  },
  getShowDate(dateLongValue) {
    return this.formatDate(new Date(parseInt(dateLongValue)), 'yyyy-MM-dd')
  },
  getShowTimeByDate(date) {
    return this.formatDate(date, 'yyyy-MM-dd hh:mm')
  },
  getShowTimeByDateString(date) {
    return date.replace(/:..$/, '')
  },
  getShowDateByDate(date) {
    return this.formatDate(date, 'yyyy-MM-dd')
  },
  getTimeLong(dateString) {
    if (dateString.indexOf(':') === -1) {
      // 只有日期
      dateString += ' 00:00:00'
    } else if (dateString.split(':').length === 2) {
      // 没有秒
      dateString += ':00'
    }
    return new Date(dateString.replace(/-/g, '/')).getTime()
  },
  getDateMinIntTimestamp(date) {
    return parseInt(date.getTime() / 100000)
  },
  getDateTimeMinIntTimestamp(date) {
    return parseInt(date.getTime() / 1000)
  },
  getDateByMinIntTimestamp(value) {
    return new Date(value * 100000)
  },
  getDateTimeByMinIntTimestamp(value) {
    return new Date(value * 1000)
  },
  getTodayDifferenceDate(number) {
    const d = new Date()
    return new Date(d.setDate(d.getDate() - number))
  },
  getToday() {
    return new Date(this.formatDate(new Date(), 'yyyy/MM/dd 00:00:00'))
  },
  getTodayEnd() {
    return new Date(this.formatDate(new Date(), 'yyyy/MM/dd 23:59:59'))
  },
  getYesterday() {
    let date = new Date()
    date = new Date(date.getTime() - this.DATE_MILLISECOND_DAY)
    return new Date(this.formatDate(date, 'yyyy/MM/dd 00:00:00'))
  },
  getYesterdayEnd() {
    let date = new Date()
    date = new Date(date.getTime() - this.DATE_MILLISECOND_DAY)
    return new Date(this.formatDate(date, 'yyyy/MM/dd 23:59:59'))
  },
  getLastWeekStart(date) {
    if (undefined === date) {
      date = new Date()
    }
    date = new Date(this.formatDate(date, 'yyyy/MM/dd 00:00:00'))
    let week
    if (date.getDay() === 0) {
      week = 7
    } else {
      week = date.getDay()
    }
    return new Date(date.getTime() - (week + 6) * this.DATE_MILLISECOND_DAY)
  },
  getLastWeekEnd(date) {
    return new Date(this.getLastWeekStart().getTime() + 518400000)
  },
  calculateTimeDifference(timestamp1, timestamp2) {
    // 确保timestamp2大于或等于timestamp1
    let diff = Math.abs(timestamp2 - timestamp1)

    // 将毫秒转换为天数、小时数和分钟数
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))
    diff -= days * (1000 * 60 * 60 * 24)
    const hours = Math.floor(diff / (1000 * 60 * 60))
    diff -= hours * (1000 * 60 * 60)
    const minutes = Math.floor(diff / (1000 * 60))

    // 返回结果对象
    return {
      days: days,
      hours: hours,
      minutes: minutes
    }
  },

  getThisMonthStart(date) {
    if (undefined === date) {
      date = new Date()
    }
    date = new Date(this.formatDate(date, 'yyyy/MM/dd 00:00:00'))
    return new Date(date.getTime() - (date.getDate() - 1) * this.DATE_MILLISECOND_DAY)
  },
  getThisMonthEnd(date) {
    if (undefined === date) {
      date = new Date()
    }
    let month = date.getMonth() + 1
    let year = date.getFullYear()
    if (month === 12) {
      year++
      month = 0
    }
    month++
    return this.getLastMonthEnd(new Date(year + '/' + month + '/1'))
  },
  getLastMonthStart(date) {
    if (undefined === date) {
      date = new Date()
    }
    let month = date.getMonth() + 1
    let year = date.getFullYear()
    if (month === 1) {
      year--
      month = 13
    }
    month--
    return new Date(year + '/' + month + '/1 00:00:00')
  },
  getLastMonthEnd(date) {
    if (undefined === date) {
      date = new Date()
    }
    date = new Date(this.formatDate(date, 'yyyy/MM/dd 23:59:59'))
    return new Date(date.getTime() - date.getDate() * this.DATE_MILLISECOND_DAY)
  },
  getBeforeYesterDay(timestamp) {
    if (timestamp === undefined) {
      timestamp = Date.now() // 你可以替换为任何你想要的时间戳
    }
    // 将时间戳转换为Date对象
    const date = new Date(timestamp)
    // 减去一天（一天的毫秒数 = 24小时 * 60分钟/小时 * 60秒/分钟 * 1000毫秒/秒）
    date.setDate(date.getDate() - 1)

    return date.getTime()
  },
  /**
   * 获取内容占空间数量（单位：半个汉字）
   * @param text
   * @returns {*}
   */
  getSpaceQuantity(text) {
    return text.replace(/[^\x00-\xff]/g, '**').length
  },
  filterFormParam(formParam) {
    const param = JSON.parse(JSON.stringify(formParam))
    for (const key in param) {
      if (key === 'notSubmit' || undefined === param[key] || param[key] === null || param[key] === '') {
        delete param[key]
      } else if (typeof param[key] === 'object') {
        for (const key2 in param[key]) {
          if (key2 === 'notSubmit') {
            delete param[key][key2]
            continue
          }
          if (typeof param[key][key2] === 'object') {
            for (const key3 in param[key][key2]) {
              if (undefined === param[key][key2][key3] || param[key][key2][key3] === null || param[key][key2][key3] === '') {
                delete param[key][key2][key3]
              }
            }
            if (JSON.stringify(param[key][key2]) === '{}' || param[key][key2].length === 0) {
              delete param[key][key2]
            }
          } else {
            if (undefined === param[key][key2] || param[key][key2] === null || param[key][key2] === '') {
              delete param[key][key2]
            }
          }
        }
        if (JSON.stringify(param[key]) === '[null]' || JSON.stringify(param[key]) === '{}') {
          delete param[key]
        }
      }
    }
    return param
  },
  getAmountByCent(amountCent) {
    return (parseFloat(amountCent) / 100).toFixed(2)
  },
  getAmountCent(amount) {
    return parseInt((parseFloat(amount) * 100) + '')
  },
  formReset(resetForm, toForm) {
    for (const i in resetForm) {
      if (!Reflect.has(resetForm, i)) {
        continue
      }
      if (i === 'notSubmit') {
        toForm[i] = JSON.parse(JSON.stringify(resetForm[i]))
      } else {
        toForm[i] = resetForm[i]
      }
    }
  },
  getNameOrLabelByArrayAndValue(array, value) {
    if (undefined === array) {
      return '参数错误';
    }
    for (let i = 0; i < array.length; i++) {
      if (array[i].value === value) {
        return undefined !== array[i].name ? array[i].name : array[i].label;
      }
    }
    return '';
  }
}

module.exports = fn
